home *** CD-ROM | disk | FTP | other *** search
- Path: jaxnet.jaxnet.com!NewsWatcher!user
- From: garyg@jax.jaxnet.com (Gary M. Greenberg)
- Newsgroups: comp.lang.c
- Subject: Re: Can anyone help a newbie out ?
- Date: Sun, 14 Apr 1996 11:18:00 -0400
- Organization: Southeast Network Services, Inc.
- Message-ID: <garyg-1404961118000001@204.183.221.242>
- References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
- NNTP-Posting-Host: ts4-000.jaxnet.com
-
- In article <4kkf3r$5b0@darwin.nbnet.nb.ca>, lewwid@brunswickmicro.nb.ca
- (Jeff) wrote:
- > Problem:Write a function that accepts two strings. Count the number
- > of characters in each string, and return the pointer to the longer
- > string.
- [code snipped]
-
- [courtesy copy emailed]
-
- Here's my very basic illustration to demonstrate a possible solution.
-
- It doesn't return a pointer to the longer string because
- the problem doesn't account for equal length inputs.
-
- Instead, it returns a string which states the size relationship.
- However, I think the code is in keeping with the spirit of the Problem.
- /*** Flamers, start your engines ;-) ***/
-
- /* longerstr.c */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define SAME "the same length as"
- #define SH "shorter than"
- #define LO "longer than"
-
- #define LEN 256 /* an _arbitrary_ string length limit */
-
- /* prototype */
- char *compstrings (char *firststring, char *secstring);
-
- int main()
- {
- char str1[LEN], str2[LEN];
- printf("Enter a string <STR1> ...\n");
- /* one should AVOID gets */
- fgets(str1,sizeof(str1),stdin);
- if(str1[strlen(str1)-1]=='\n')
- str1[strlen(str1)-1]='\0';
- printf("Enter a string <STR2> ...\n");
- fgets(str2,sizeof(str2),stdin);
- if(str2[strlen(str2)-1]=='\n')
- str2[strlen(str2)-1]='\0';
- printf("String '%s' <STR1> is %s string '%s' <STR2>\n",str1,
- compstrings(str1,str2),str2);
- return EXIT_SUCCESS;
- }
-
- char *compstrings(char *firststring, char *secstring)
- {
- char *res;
-
- if(strlen(firststring)==strlen(secstring))
- if((res=malloc(strlen(SAME)))==NULL) {
- printf("No memory for SAME.\n");
- exit EXIT_FAILURE;
- }
- else
- strcpy(res,SAME);
-
- else if (strlen(firststring)>strlen(secstring))
- if((res=malloc(strlen(LO)))==NULL) {
- printf("No memory for LO.\n");
- exit EXIT_FAILURE;
- }
- else
- strcpy(res,LO);
-
- else
- {
- if((res=malloc(strlen(SH)))==NULL) {
- printf("No memory for SH.\n");
- exit EXIT_FAILURE;
- }
- else
- strcpy(res,SH);
- }
-
- return res;
- }
- /* end of longerstr.c */
-
- gary /* the Sorcerer's Apprentice */
- Contribute to the Randal Schwatrz Legal Defense Fund by
- Visit this site && grab free E-Mail Management Source Code
- http:/jax.jaxnet.com/~garyg/main_page.html
-